package org.senseframework.support.lucene.core;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by lanjian on 2015/4/28.
 */
public class DocumentContext implements InitializingBean {

    private static Log log= LogFactory.getLog(DocumentContext.class);

    private static Map<Class,DocumentDefinition> classDocumentDefinitionMap=new HashMap<Class,DocumentDefinition>();

    private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);


    public static DocumentDefinition  findDocumentDefinition(Class clazz){
        DocumentDefinition documentDefinition=classDocumentDefinitionMap.get(clazz);
        if(documentDefinition==null){
            throw new RuntimeException(clazz.getSimpleName()+" document not found");
        }
        return documentDefinition;
    }

    public void afterPropertiesSet() throws Exception {
        if(dataRunners==null || dataRunners.isEmpty()){
            return;
        }
        register();
        start();
    }

    private void start(){
        for(final DataRunner dataRunner:dataRunners){
            scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    try {
                        log.info(dataRunner.clazz().getSimpleName()+" start ");
                        DocumentDefinition documentDefinition=findDocumentDefinition(dataRunner.clazz());
                        documentDefinition.index(dataRunner);
                    } catch (Exception ex) {
                        log.error(dataRunner.clazz().getSimpleName()+" start ",ex);
                    }
                }
            }, 1, dataRunner.time(), TimeUnit.SECONDS);
        }
    }

    private void register(){
        for(final DataRunner dataRunner:dataRunners){
            if(classDocumentDefinitionMap.containsKey(dataRunner.clazz())){
                throw new RuntimeException("double register dataRunner");
            }
            classDocumentDefinitionMap.put(dataRunner.clazz(), new DocumentDefinition(dataRunner.clazz()));
        }
    }

    public List<DataRunner> dataRunners;

    public List<DataRunner> getDataRunners() {
        return dataRunners;
    }

    public void setDataRunners(List<DataRunner> dataRunners) {
        this.dataRunners = dataRunners;
    }
}
